package com.ntes.consumer1.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.ntes.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Created by bjliuyue1 on 2017/5/19.
 */
@Service
public class DemoService {

    private int flag = 0;
    @Autowired
    RestTemplate restTemplate;

    /**
     * @HystrixCommand注解的属性
     * fallbackMethod 降级方法
     * commandProperties 普通配置属性，可以配置HystrixCommand对应属性，例如采用线程池还是信号量隔离、熔断器熔断规则等等
     * ignoreExceptions 忽略的异常，默认HystrixBadRequestException不计入失败
     * groupKey() 组名称，默认使用类名称
     * commandKey 命令名称，默认使用方法名
     * 降级方法的返回值不一致时，不会提示，调用时会报错;
     * 参数列表需要一致，否则报错 FallbackDefinitionException: fallback method wasn't found
     */
    @HystrixCommand(fallbackMethod = "stringFallBack")
    public String string(String name) {
        return restTemplate.getForObject("http://SERVICE-DEMO/getString?name=" + name, String.class);
    }

    public String stringFallBack(String name) {
        return "stringFallBack " + name;
    }

    @HystrixCommand(fallbackMethod = "userFallBack")
    public User user(String name) {
        return restTemplate.getForObject("http://SERVICE-DEMO/getUser?name=" + name, User.class);
    }

    public User userFallBack(String name) {
        User user = new User();
        user.setName("default" + name);
        user.setAge(1800);
        user.setPort(1010);
        return user;
    }

    @HystrixCommand(fallbackMethod = "userStringFallBack", ignoreExceptions = NumberFormatException.class)
    public String userString(String name) {
        flag++;
        if ((flag % 3) == 0) {
            System.out.println("userString throw NumberFormatException");
            throw new NumberFormatException();
        }
        else if ((flag % 3) == 1) {
            System.out.println("userString throw Exception");
            throw new RuntimeException();
        }
        else {
            return restTemplate.getForObject("http://SERVICE-DEMO/getUser?name=" + name, String.class);
        }
    }

    public String userStringFallBack(String name) {
        return name + " error userStringFallBack";
    }

    @HystrixCommand
    public String getString(String name) {
        return restTemplate.getForObject("http://SERVICE-DEMO1/getString?name=" + name, String.class);
    }
}
